#!/bin/bash

# SmartInput 可配置启动脚本
# 使用方法: ./start-with-config.sh [环境]

ENVIRONMENT=${1:-development}

echo "启动 SmartInput 系统 (环境: $ENVIRONMENT)"

# 设置默认环境变量
export SERVER_PORT=8080
export SERVER_ADDRESS=0.0.0.0
export SSL_ENABLED=false
export CORS_ALLOWED_ORIGINS="http://localhost:5173,http://localhost:3003,http://192.168.3.17:5173,http://192.168.3.17:3003"
export CORS_ALLOWED_METHODS="GET,POST,PUT,DELETE,OPTIONS"
export CORS_ALLOWED_HEADERS="*"
export WS_ALLOWED_ORIGINS="http://localhost:5173,http://localhost:3003,http://192.168.3.17:5173,http://192.168.3.17:3003"

# 根据环境设置不同的配置
case $ENVIRONMENT in
  "development")
    echo "使用开发环境配置..."
    export VITE_API_BASE_URL="http://localhost:8080"
    export VITE_WS_BASE_URL="ws://localhost:8080"
    export VITE_DEV_SERVER_PORT=5173
    export VITE_DEV_SERVER_HOST=localhost
    ;;
  "production")
    echo "使用生产环境配置..."
    export SERVER_PORT=8443
    export SSL_ENABLED=true
    export VITE_API_BASE_URL="https://your-domain.com:8443"
    export VITE_WS_BASE_URL="wss://your-domain.com:8443"
    export CORS_ALLOWED_ORIGINS="https://your-domain.com"
    export WS_ALLOWED_ORIGINS="https://your-domain.com"
    ;;
  "local")
    echo "使用本地环境配置..."
    export VITE_API_BASE_URL="http://192.168.3.17:8080"
    export VITE_WS_BASE_URL="ws://192.168.3.17:8080"
    export VITE_DEV_SERVER_PORT=3003
    export VITE_DEV_SERVER_HOST=0.0.0.0
    export VITE_HMR_HOST=192.168.3.17
    ;;
  *)
    echo "未知环境: $ENVIRONMENT"
    echo "可用环境: development, production, local"
    exit 1
    ;;
esac

echo "配置信息:"
echo "  后端端口: $SERVER_PORT"
echo "  后端地址: $SERVER_ADDRESS"
echo "  API地址: $VITE_API_BASE_URL"
echo "  WebSocket地址: $VITE_WS_BASE_URL"
echo "  前端端口: $VITE_DEV_SERVER_PORT"
echo "  前端地址: $VITE_DEV_SERVER_HOST"

# 启动后端
echo "启动后端服务..."
cd backend
./gradlew bootRun &
BACKEND_PID=$!

# 等待后端启动
sleep 10

# 启动前端
echo "启动前端服务..."
cd ../frontend
npm run dev &
FRONTEND_PID=$!

# 启动移动端
echo "启动移动端服务..."
cd ../mobile-app
npm run dev &
MOBILE_PID=$!

echo "所有服务已启动!"
echo "  后端 PID: $BACKEND_PID"
echo "  前端 PID: $FRONTEND_PID"
echo "  移动端 PID: $MOBILE_PID"
echo ""
echo "访问地址:"
echo "  前端: http://$VITE_DEV_SERVER_HOST:$VITE_DEV_SERVER_PORT"
echo "  移动端: http://$VITE_DEV_SERVER_HOST:3003"
echo "  后端API: $VITE_API_BASE_URL"
echo ""
echo "按 Ctrl+C 停止所有服务"

# 等待用户中断
trap "echo '正在停止服务...'; kill $BACKEND_PID $FRONTEND_PID $MOBILE_PID; exit" INT
wait 